<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="搅拌站名称" prop="mixingStationCode">
          <el-select v-model="queryParams.mixingStationCode" placeholder="请选择搅拌站名称" clearable class="!w-220px">
            <el-option v-for="(item, index) in mixingStationOptions" :key="index" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>

        <el-form-item label="参数名称" prop="keyNameFuzzy">
          <el-input v-model="queryParams.keyNameFuzzy" placeholder="请输入参数名称" clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><ep-Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><ep-Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex-x-b">
          <el-button type="success" @click="handleOpenDialog()">
            <template #icon><ep-Plus /></template>
            新增
          </el-button>
        </div>
      </template>

      <el-table v-auto-h v-loading="loading" :data="tableData" border>
        <el-table-column label="搅拌站名称" align="center" prop="mixingStationName" />
        <el-table-column label="搅拌站编号" align="center" prop="mixingStationCode" />
        <el-table-column label="参数名称" align="center" prop="keyName" />
        <el-table-column label="参数值" align="center" prop="val" />
        <el-table-column label="单位" min- align="center" prop="uom" />
        <el-table-column label="更新人" align="center" prop="updateBy" />
        <el-table-column label="更新时间" align="center" prop="updateTime" />

        <el-table-column fixed="right" label="操作" width="100" align="center">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleOpenDialog(row)">
              <template #icon><ep-Edit /></template>
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-model:page="current" v-model:pagesize="pageSize" :total="total" />
    </el-card>

    <!-- 编辑表单弹框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="搅拌站名称" prop="mixingStationCode">
          <el-select v-model="formData.mixingStationCode" placeholder="请选择搅拌站名称" :disabled="!!formId">
            <el-option v-for="item in mixingStationOptions" :key="item.number" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>
        <el-form-item label="参数名称" prop="configKey">
          <el-select v-model="formData.configKey" placeholder="请选择参数名称" :disabled="!!formId" @change="handleSelectParameter">
            <el-option v-for="item in parameterOptions" :key="item.configKey" :label="item.keyName" :value="item.configKey" />
          </el-select>
        </el-form-item>

        <el-form-item label="参数值" prop="val">
          <el-input v-model="formData.val" placeholder="请输入参数值" />
        </el-form-item>

        <el-form-item label="单位" prop="uom">
          <el-input v-model="formData.uom" placeholder="请输入单位" disabled />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { useRequest, usePagination } from '@/hooks/useRequest'
import type { FormInstance } from 'element-plus'
import { getPage, update, add, getParameterList } from '@/api/parameter/parameter'
import type { ParameterPageQuery, Data, Form } from '@/api/parameter/parameter'
import { getMixingStationList, type MixingStationData } from '@/api/customer/customer'

import Storage from '@/utils/Storage'
import { DEFAULT_MIXING_STATION_ID_KEY } from '@/utils/constant'

const queryFormRef = ref<FormInstance>()

const queryParams = reactive<ParameterPageQuery>({ nowPage: 1, pageSize: 10 })

const { data, loading, run, total, current, pageSize } = usePagination(getPage, { defaultParams: [queryParams], manual: true })

const tableData = computed(() => data.value?.result.records || [])

const handleQuery = () => {
  run(queryParams)
}

const handleResetQuery = () => {
  queryFormRef.value!.resetFields()
  handleQuery()
}

// 获取搅拌站下拉数据
const { data: mixingStationData } = useRequest(getMixingStationList, {
  onSuccess({ result }) {
    if (result && result.length) {
      let defaultMixingStation: MixingStationData = null
      const defaultMixingStationId = Storage.getStorage(DEFAULT_MIXING_STATION_ID_KEY)

      // 先从本地缓存匹配搅拌站数据；如果能找到数据，则说明该用户有本地缓存搅拌站的权限
      if (defaultMixingStationId) {
        defaultMixingStation = result.find(item => item.id === defaultMixingStationId)
      }

      // 如果无缓存或者无法匹配到数据；则默认取第一个数据并重新设置缓存
      if (!defaultMixingStation) {
        defaultMixingStation = result[0]
        Storage.setStorage(DEFAULT_MIXING_STATION_ID_KEY, defaultMixingStation.id)
      }

      queryParams.mixingStationCode = defaultMixingStation.number
    }
  },
  onAfter() {
    handleQuery()
  }
})
const mixingStationOptions = computed(() => mixingStationData.value?.result || [])

// 获取参数下拉数据
const { data: parameterData } = useRequest(getParameterList)
const parameterOptions = computed(() => parameterData.value?.result || [])

// 选择参数名称
const handleSelectParameter = (value: string) => {
  formData.uom = parameterOptions.value.find(item => item.configKey === value)?.uom
}

/** --------------------- 编辑部分 -------------------- */
const dialog = reactive({
  title: '',
  visible: false
})

const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const formData = reactive<Form>({})

const rules = reactive({
  mixingStationCode: [{ required: true, message: '请选择搅拌站名称', trigger: 'change' }],
  configKey: [{ required: true, message: '请选择参数名称', trigger: 'change' }],
  val: [{ required: true, message: '请输入参数值', trigger: 'blur' }],
  uom: [{ required: true, message: '请输入单位', trigger: 'change' }]
})

const formId = computed(() => formData.id)

const handleOpenDialog = async (row?: Data) => {
  dialog.visible = true
  if (row) {
    dialog.title = '编辑基础参数'
    await nextTick()
    Object.assign(formData, row)
  } else {
    dialog.title = '新增基础参数'
  }
}

const handleCloseDialog = () => {
  dialog.visible = false
  formRef.value.resetFields()
  formData.id = undefined
}

const handleSubmit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      submitLoading.value = true
      const fetchFn = formId.value ? update : add
      fetchFn(formData)
        .then(() => {
          ElMessage.success(formId.value ? '修改成功' : '新增成功')
          handleCloseDialog()
          handleQuery()
        })
        .finally(() => (submitLoading.value = false))
    }
  })
}
</script>
<style lang="scss" scoped></style>
